package com.example.studyonlineapplication;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;

import com.example.studyonlineapplication.domain.po.Result;
import com.example.studyonlineapplication.domain.po.User;
import com.example.studyonlineapplication.utils.MyToast;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.concurrent.CountDownLatch;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class Login extends AppCompatActivity {

    Button reAndLgBtn,changeStateBtn;
    EditText usrEt,pwdEt,rePwdEt;
    CheckBox remMeCb;
    CardView rePwdView;
    OkHttpClient client = new OkHttpClient();
    Request request;
    String url = "http://10.0.2.2:8080/user";


    Result<User> data;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_page);
        init();
        initEvent();
    }

    private void init(){
        reAndLgBtn = findViewById(R.id.rgAndLg);
        usrEt = findViewById(R.id.usr);
        pwdEt = findViewById(R.id.pwd);
        rePwdEt = findViewById(R.id.rePwd);
        remMeCb = findViewById(R.id.remMe);
        changeStateBtn = findViewById(R.id.changeState);
        rePwdView = findViewById(R.id.rePwdView);
        request = new Request.Builder()
                .url(url)
                .build();
    }

    private  void initEvent(){
        changeStateBtn.setOnClickListener(v->{
            if(reAndLgBtn.getText().toString().equals("登录")){
                rePwdView.setVisibility(View.VISIBLE);
                changeStateBtn.setText("返回");
                reAndLgBtn.setText("注册");
            }
            else{
                rePwdView.setVisibility(View.GONE);
                changeStateBtn.setText("注册账户");
                reAndLgBtn.setText("登录");
            }
            usrEt.setText("");
            pwdEt.setText("");
            rePwdEt.setText("");
        });

        reAndLgBtn.setOnClickListener(v->{
            //登录
            if(reAndLgBtn.getText().toString().equals("登录")){
                String s1 = usrEt.getText().toString();
                String s2 = pwdEt.getText().toString();
                RequestBody body = new FormBody.Builder()
                        .add("username", s1)
                        .add("password", s2)
                        .build();
                request = new Request.Builder()
                        .url(url+"/login")
                        .post(body)
                        .build();
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                        String responseData = response.body().string();
                        Type resultType = new TypeToken<Result<User>>() {}.getType(); // 定义 Result<User> 的类型
                        Gson gson = new Gson();
                        data = gson.fromJson(responseData, resultType);

                        runOnUiThread(() -> {
                            if(data.getCode()==1){
                                MyToast.message(data.getMessage(),Login.this);
                            }
                            else{
                                SharedPreferences sp = getSharedPreferences("data",MODE_PRIVATE);
                                sp.edit().putString("user",gson.toJson(data.getData())).apply();
                                MyToast.message("登录成功",Login.this);
                                startActivity(new Intent(Login.this,AppActivityMain.class));
                                finish();
                            }
                        });
                    }
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        e.printStackTrace();
                    }
                });
            }
            //注册
            else{
                String s1 = usrEt.getText().toString();
                String s2 = pwdEt.getText().toString();
                String s3 = rePwdEt.getText().toString();
                RequestBody body = new FormBody.Builder()
                        .add("username", s1)
                        .add("password", s2)
                        .add("repwd",s3)
                        .build();
                request = new Request.Builder()
                        .url(url+"/register")
                        .post(body)
                        .build();
                System.out.println(url+"/register");
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                        String responseData = response.body().string();
                        System.out.println(responseData);
                        data= new Gson()
                                .fromJson(responseData, Result.class);
                        runOnUiThread(() -> {
                            if(data.getCode()==1){
                                MyToast.message(data.getMessage(),Login.this);
                            }
                            else{
                                MyToast.message("注册成功",Login.this);
                            }
                        });
                    }
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        e.printStackTrace();
                    }
                });

            }
        });

    }





}
